/*
 * 企业列表
 * @Author: along
 * @Date: 2019-12-09 10:24:00
 */
<template>
    <div class="container companyList">
        <!-- header -->
        <div class="headerBox">
            <div class="header-left">
                <div class="header-box">
                    <el-radio-group
                        v-model="searchType"
                        @change="getTableData(1)"
                        size="small"
                    >
                        <el-radio-button label="1">商城</el-radio-button>
                        <el-radio-button label="2">工作</el-radio-button>
                        <el-radio-button label="3">学习</el-radio-button>
                    </el-radio-group>
                </div>
                <div class="header-box">
                    <p class="header-box-title">状态:</p>
                    <el-select
                        v-model="status"
                        filterable
                        placeholder="请选择"
                        size="small"
                        clearable
                        @change="getTableData(1)"
                    >
                        <el-option
                            v-for="item in statusList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </div>
                <div class="header-box">
                    <p class="header-box-title">名称:</p>
                    <el-input
                        v-model="name"
                        placeholder="请输入内容"
                        suffix-icon="el-icon-search"
                        size="small"
                        clearable
                        @change="getTableData(1)"
                        @keyup.native.enter="getTableData(1)"
                    />
                </div>
            </div>
            <div class="header-box">
                <el-button
                    type="primary"
                    size="small"
                    @click="fnOpenAddHot()"
                >新增</el-button>
            </div>
        </div>
        <!-- /header -->

        <!-- table -->
        <el-table
            :data="tableData"
            height="100%"
            style="width: 100%;"
            border
            ref="companyList"
        >
            <el-table-column
                type="index"
                width="80"
                label="序号"
                align="center"
            />
            <el-table-column
                prop="keyword"
                label="名称"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            />
            <el-table-column
                prop="start_time"
                label="使用时间"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            >
                <template slot-scope="scope">
                    <span>{{ scope.row.start_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm') }} - {{ scope.row.end_time * 1000 | dateFormatter('yyyy/MM/dd HH:mm') }}</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="keyword_status"
                label="状态"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            >
                <template slot-scope="scope">
                    <span v-if="scope.row.keyword_status == 1">已启用</span>
                    <span v-if="scope.row.keyword_status == 0">未启用</span>
                </template>
            </el-table-column>
            <el-table-column
                prop="keyword_expire"
                label="过期状态"
                show-overflow-tooltip
                :formatter="emptyFormatter"
                align="center"
            >
                <template slot-scope="scope">
                    <span v-if="scope.row.keyword_expire == -1">未开始</span>
                    <span v-if="scope.row.keyword_expire == 0">生效中</span>
                    <span v-if="scope.row.keyword_expire == 1">已过期</span>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
            >
                <template slot-scope="scope">
                    <el-button
                        type="text"
                        class="curse-add"
                        @click="fnSetStatus(scope.row)"
                    >
                        <span v-if="scope.row.keyword_status == 0">启用</span>
                        <span v-if="scope.row.keyword_status == 1">取消启用</span>
                    </el-button>
                    <el-button
                        type="text"
                        class="curse-add"
                        @click="fnEditData(scope.row)"
                    >
                        编辑
                    </el-button>
                    <el-button
                        type="text"
                        class="curse-add"
                        @click="fnDeleteData(scope.row)"
                    >
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- /table -->

        <!-- 新增弹窗 -->
        <el-dialog
            title="新增搜索框搜索词"
            :visible.sync="dialogVisible"
            width="520px"
            :close-on-click-modal="false"
        >
            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="80px"
                class="demo-ruleForm"
            >
                <el-form-item
                    label="类型"
                >
                    <el-radio
                        v-model="searchType"
                        label="1">商城</el-radio>
                    <el-radio
                        v-model="searchType"
                        label="2">工作</el-radio>
                    <el-radio
                        v-model="searchType"
                        label="3">学习</el-radio>
                </el-form-item>
                <el-form-item
                    label="标题"
                    prop="title"
                >
                    <el-input
                        v-model="ruleForm.title"
                        size="small"
                        placeholder="最多不超过10个字"
                    />
                </el-form-item>
                <el-form-item
                    label="展示时间"
                    prop="time"
                >
                    <el-date-picker
                        v-model="ruleForm.time"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        size="small"
                    />
                </el-form-item>
            </el-form>
            <span
                slot="footer"
                class="dialog-footer">
                <el-button
                    @click="dialogVisible = false"
                    size="small"
                >取 消</el-button>
                <el-button
                    type="primary"
                    @click="fnAddHot('ruleForm')"
                    size="small"
                    :disabled="isButton"
                >确 定</el-button>
            </span>
        </el-dialog>
        <!-- /新增弹窗 -->

    </div>
</template>

<script>
import {getDate} from '@/assets/js/utils.js';
export default {
    /**
     * @param  {Object}    authResult           //表单权限
     * @param  {Array}     tableData            //表单数据
     * @param  {Object}    page                 //表单分页
     * @param  {String}    searchType           //热词tab
     * @param  {String}    status               //热词启用状态
     * @param  {Array}     statusList           //热词启用状态数据
     * @param  {String}    name                 //热词搜索字段
     * @param  {Boolean}   dialogVisible        //弹窗开关
     * @param  {Object}    rules                //弹窗验证规则
     * @param  {Object}    ruleForm             //弹窗字段
     * @param  {Boolean}   isButton             //弹窗确认按钮是否可点击
     */
    data () {
        return {
            enablestatus: '',
            editTime: {
                start_time: '',
                end_time: ''
            },
            enableTime: [],
            enable: false,
            id: '',
            type: '',
            isButton: true,
            ruleForm: {
                title: '',
                time: ''
            },
            rules: {
                title: [
                    {required: true, message: '请输入标题,不可以为空', trigger: 'blur'}
                ],
                time: [
                    {required: true, message: '请选择时间,不可以为空', trigger: 'blur'}
                ]
            },
            dialogVisible: false,
            name: '',
            statusList: [{
                value: '',
                label: '全部'
            },{
                value: 1,
                label: '已启用'
            },{
                value: 0,
                label: '未启用'
            }],
            status: '',
            searchType: '1',
            page: {
                now_page: 1,
                total_count: 0,
                page_size: 0
            },
            tableData: [],
            authResult: {}
        };
    },
    filters: {},
    computed: {},
    watch: {
        ruleForm: {
            deep: true,
            handler: function (resp) {
                if (resp.title == '') {
                    this.isButton = true;
                } else {
                    this.isButton = false;
                }
            }
        },
        dialogVisible (val) {
            if (!val) {
                this.ruleForm = {
                    title: '',
                    time: []
                };
                this.$refs['ruleForm'].resetFields();
            }
        }
    },
    mounted () {
        this.authResult = this.$route.meta.authResult;
        this.fnBreadcrumb();
        this.getTableData();
    },
    methods: {
        /**
         * 设置表单header
         */
        fnBreadcrumb () {
            this.$store.commit('SET_HEADER', [{ title: "APP后台"},{title: '热门搜索'},{title: "搜索框默认词"}]);
        },

        /**
         * 获取表格数据
         */
        getTableData (page) {
            this.$post('/student/search_default_keyword%5Cget_list', {
                type: this.searchType,
                keyword_status: this.status,
                keyword: this.name
            }, resp => {
                if (resp.code == 1) {
                    this.tableData = resp.data.list;

                    //查询当前是否有启用状态,一个分类最多启用一个
                    let count = 0;

                    this.enableTime = [];
                    this.tableData.map(item=>{
                        if (Number(item.keyword_status) == 1) {
                            count ++ ;
                            this.enableTime.push({
                                start_time: item.start_time,
                                end_time: item.end_time
                            });
                        }
                    });

                    if (count > 0) { //当前有启用热词
                        this.enable = true;
                    } else { //当前没有启用热词
                        this.enable = false;
                    }
                }
            });
        },

        /**
         * 打开新增弹窗
         */
        fnOpenAddHot () {
            this.type = 'addHot';
            this.dialogVisible = !this.dialogVisible;
        },

        /**
         * 新增热词
         */
        fnAddHot (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let data = {};

                    if (this.type == 'addHot') {
                        data = {
                            id: '',
                            type: this.searchType,
                            keyword: this.ruleForm.title,
                            start_time: getDate(new Date(this.ruleForm.time[0]).getTime()),
                            end_time: getDate(new Date(this.ruleForm.time[1]).getTime())
                        };
                    } else if (this.type == 'edithot') {
                        let start_time = getDate(new Date(this.ruleForm.time[0]).getTime());
                        let end_time = getDate(new Date(this.ruleForm.time[1]).getTime());

                        if (this.enable && Number(this.enablestatus) == 1) {
                            let arr = this.enableTime;
                            let newArr = [];

                            arr.map(item=>{
                                if (item.start_time == this.editTime.start_time && item.end_time == this.editTime.end_time) {
                                    //
                                } else {
                                    newArr.push({
                                        start_time: item.start_time,
                                        end_time: item.end_time
                                    });
                                }
                            });

                            for(let i=0; i<newArr.length; i++) {
                                if (start_time > newArr[i].start_time && start_time < newArr[i].end_time || end_time > newArr[i].start_time && end_time < newArr[i].end_time) {
                                    this.$message({
                                        type: 'message',
                                        message: '同一时间内，只能设置一个热词',
                                        center: true
                                    });
                                    return;
                                }
                            }
                        }
                        data = {
                            id: this.id,
                            type: this.searchType,
                            keyword: this.ruleForm.title,
                            start_time: start_time,
                            end_time: end_time
                        };
                    } else {
                        return;
                    }

                    this.$post('/student/search_default_keyword%5Csave',{
                        ...data
                    },resp=> {
                        if (resp.code == 1) {
                            this.getTableData();
                            this.dialogVisible = !this.dialogVisible;
                            this.$message({
                                type: 'success',
                                message: resp.msg,
                                center: true
                            });
                        } else if (resp.code == 0) {
                            this.$message({
                                type: 'waring',
                                message: resp.msg,
                                center: true
                            });
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },

        /**
         * 设置启用状态
         */
        fnSetStatus (row) {
            // if (this.enable && Number(row.keyword_status) == 0) {
            //     let arr = this.enableTime;

            //     for(let i=0; i<arr.length; i++) {
            //         if (row.start_time >= arr[i].start_time && row.start_time <= arr[i].end_time || row.end_time >= arr[i].start_time && row.end_time <= arr[i].end_time) {
            //             this.$message({
            //                 type: 'message',
            //                 message: '同一时间内，只能设置一个热词',
            //                 center: true
            //             });
            //             return;
            //         }
            //     }
            // }

            let message = '';

            if (row.keyword_status == 0) {
                message = '启用成功!';
                this.$confirm('启用后该搜索词将展示在APP的对应搜索框内，确认启用？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.setStatus(row, message);
                });
            } else if (row.keyword_status == 1) {
                message = '取消成功!';
                this.$confirm('取消启用后该搜索词将不再展示在APP的对应搜索框内，确认取消？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.setStatus(row, message);
                });
            }
        },
        setStatus (row,message) {
            this.$post('/student/search_default_keyword%5Cset_status',{
                id: row.id,
                keyword_status: row.keyword_status == 1 ? 0 : 1
            },resp=>{
                if (resp.code == 1) {
                    this.getTableData();
                    this.$message({
                        type: 'success',
                        message: message,
                        center: true
                    });
                } else if (resp.code == 0) {
                    this.$message({
                        type: 'warning',
                        message: resp.msg,
                        center: true
                    });
                }
            });
        },

        /**
         * 编辑热词
         */
        fnEditData (row) {
            this.type = 'edithot';
            this.enablestatus = row.keyword_status;
            this.id = row.id;
            this.$post('/student/search_default_keyword%5Cget',{
                id: row.id
            },resp=>{
                if (resp.code == 1) {
                    let time = [];

                    if (resp.data.start_time !== 0 || resp.data.end_time !== 0) {
                        time= [
                            new Date(resp.data.start_time * 1000),
                            new Date(resp.data.end_time * 1000)
                        ];
                    }
                    this.ruleForm = {
                        title: resp.data.keyword,
                        time
                    };
                    //记录当前数据
                    this.editTime = {
                        start_time: row.start_time,
                        end_time: row.end_time
                    };
                    this.dialogVisible = !this.dialogVisible;
                }
            });
        },

        /**
         * 删除热词
         */
        fnDeleteData (row) {
            this.$confirm('删除后该搜索词不可恢复，确认删除？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$post('/student/search_default_keyword%5Cdelete',{
                    id: row.id
                },resp=>{
                    if (resp.code == 1) {
                        this.getTableData();
                        this.$message({
                            type: 'success',
                            message: '删除成功',
                            center: true
                        });
                    } else if (resp.code == 0) {
                        this.$message({
                            type: 'warning',
                            message: resp.msg,
                            center: true
                        });
                    }
                });
            });
        },

        /**
         * 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) return '--';
            return val;
        }
    }
};
</script>

<style lang="less" scoped>
    .container {
        background-color: #fff;
        padding: 10px 15px 5px 15px;
        display: flex;
        flex-direction: column;
        position: relative;
        width: 100%;
        .headerBox {
            position: relative;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: space-between;
            .header-left {
                display: flex;
                height: 32px;
                align-items: center;
            }
            .header-box {
                display: flex;
                margin-right: 15px;
                align-items: center;
                color: #606266;
                margin-bottom: 10px;
                &-title {
                    margin-right: 2px;
                    white-space: nowrap;
                }
            }
        }
        /* 表单 */
        .scope-price {
            width: 50px;
            height: 50px;
        }
        /* 字体高亮 */
        .cursor-font {
            color: rgb(64, 158, 255);
            cursor: pointer;
        }
        /* 分页 */
        .pagination-wrapper {
            padding-top: 10px;
            padding-bottom: 10px;
            .el-pagination {
                float: right;
                padding: 0;
                background-color: transparent;
            }
        }
    }
    /* 排序 */
    .sort-wrap {
        display: flex;
        align-items: center;
        cursor: pointer;
        .sort-spliter {
            width: 1px;
            height: 12px;
            background: rgba(235, 235, 235, 1);
            margin: 0 10px;
            }
            .btn-sort {
            font-size: 14px;
            line-height: 1;
            color: #ccc;
            &:hover {
                color: #20a0ff;
            }
        }
    }
</style>
<style lang="less">
    .companyList .el-table__body-wrapper .el-table__body .el-table__row td {
        border-right: none;
    }
    .companyList .el-table__header-wrapper .el-table__header .has-gutter tr th {
        border-right: none;
    }
    .companyList .el-table .el-table_1_column_6  .cell {
        position: relative;
    }
    .companyList .el-range-editor--small .el-range-separator{
        padding: 0 1px !important;
    }
</style>